import bpy
from bpy.types import Menu, Operator
import tempfile
import os
import json

web_meassage = {"sendclient":"blender",'to':'maya',"data":{}}




def export_selected_meshes_separately():
    selected_objects = bpy.context.selected_objects
    mesh_objects = [obj for obj in selected_objects if obj.type == 'MESH']
    
    if not mesh_objects:
        print("没有选择MESH类型的对象")
        return []
    
    temp_dir = tempfile.gettempdir()
    results = []
    original_selection = bpy.context.selected_objects
    original_active = bpy.context.view_layer.objects.active
    
    try:
        for obj in mesh_objects:
            bpy.ops.object.select_all(action='DESELECT')
            obj.select_set(True)
            bpy.context.view_layer.objects.active = obj
            
            export_path = os.path.join(temp_dir, f"{obj.name}.fbx")
            
            try:
                bpy.ops.export_scene.fbx(
                    filepath=export_path,
                    use_selection=True,
                    # 命名相关设置
                    use_active_collection=False,  # 不使用活动集合
                    global_scale=1.0,
                    apply_unit_scale=True,
                    apply_scale_options='FBX_SCALE_ALL',
                    axis_forward='-Z',
                    axis_up='Y',
                    mesh_smooth_type='FACE',  # 保持面平滑
                    use_mesh_modifiers=True,  # 应用修改器
                    use_mesh_edges=False,     # 不导出边缘数据（减少文件大小）
                    use_tspace=False,         # 不导出切线空间（Maya可以自己生成）
                    # UV和材质
                    add_leaf_bones=False,     # 禁用不必要的叶骨骼
                    bake_anim=False,         # 不导出动画
                    path_mode='AUTO',         # 自动处理纹理路径
                    embed_textures=False,     # 不嵌入纹理
                    # 对象类型
                    object_types={'MESH'},    # 只导出网格
                    # 关键设置：保留命名层级
                    use_custom_props=False,   # 不需要自定义属性
                    use_metadata=False,       # 不需要元数据
                    primary_bone_axis='Y',
                    secondary_bone_axis='X'
                )
                print(f"成功导出: {export_path}")
                results.append((obj.name, export_path))
            except Exception as e:
                print(f"导出 {obj.name} 失败: {str(e)}")
    finally:
        bpy.ops.object.select_all(action='DESELECT')
        for obj in original_selection:
            obj.select_set(True)
        bpy.context.view_layer.objects.active = original_active
    
    return results



def send_to_maya():
    export_results = export_selected_meshes_separately()
        
    if not export_results:
        print({'WARNING'}, "No mesh objects selected")
        return {'CANCELLED'}
    else:
        web_meassage['data'] = export_results
        print(web_meassage)
        send_to_file(web_meassage)
    for model_name, export_path in export_results:
        print(f"Exported: {model_name} -> {export_path}")
    
    print({'INFO'}, f"Exported {len(export_results)} objects")
    return {'FINISHED'}


def send_to_file(message):
    import tempfile
    import os
    import uuid
    
    # 确保交换目录存在
    exchange_dir = os.path.join(tempfile.gettempdir(), "BlenderToMaya")
    os.makedirs(exchange_dir, exist_ok=True)
    
    # 创建唯一的文件名
    filename = f"blender_message_{uuid.uuid4()}.json"
    file_path = os.path.join(exchange_dir, filename)
    
    # 写入消息数据
    with open(file_path, 'w') as f:
        json.dump(message, f)
    
    print(f"消息已写入文件: {file_path}")

def start_file_listener():
    import os
    import tempfile
    import bpy
    
    exchange_dir = os.path.join(tempfile.gettempdir(), "MayaToBlender")
    os.makedirs(exchange_dir, exist_ok=True)
    
    def check_for_messages():
        # 检查目录中的所有文件
        for filename in os.listdir(exchange_dir):
            if filename.endswith('.json'):
                file_path = os.path.join(exchange_dir, filename)
                try:
                    with open(file_path, 'r') as f:
                        message = json.load(f)
                    # 处理消息
                    if message.get('to') == 'blender':
                        for model_info in message.get('data', []):
                            if len(model_info) >= 2:
                                fbx_path = model_info[1].replace('\\','/')
                                fbx_path = model_info[1].replace('\\','/')
                                base_name = model_info[0]
                                
                                # 安全删除同名模型
                                objects_to_remove = [obj for obj in bpy.data.objects if obj.name == base_name]
                                for obj in objects_to_remove:
                                    try:
                                        bpy.data.objects.remove(obj)
                                    except:
                                        pass
                                
                                # 导入新模型
                                bpy.ops.import_scene.fbx(filepath=fbx_path)
                                
                                # 获取导入的物体并处理命名
                                imported_objects = list(bpy.context.selected_objects)
                                
                                # 重命名新导入的对象
                                for obj in imported_objects:
                                    try:
                                        if obj.name.startswith(base_name+".") or \
                                           obj.name == base_name.encode('unicode-escape').decode()+".001":
                                            obj.name = base_name
                                    except:
                                        print(f"重命名对象 {obj.name} 时出错")
                                
                                # 重命名新导入的对象
                                for obj in imported_objects:
                                    if obj.name.startswith(base_name+"."):
                                        obj.name = base_name
                                    elif obj.name == base_name.encode('unicode-escape').decode()+".001":
                                        obj.name = base_name
                                print(f"成功导入 {fbx_path}")
                    # 删除已处理的文件
                    os.remove(file_path)
                except Exception as e:
                    print(f"处理文件 {filename} 时出错: {str(e)}")
        return 2  # 2秒后再次检查
    
    # 使用Blender的定时器系统，避免线程
    bpy.app.timers.register(check_for_messages)
    print("文件监听已启动")